import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormDigit,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProTable
} from "@ant-design/pro-components";
import {Button, Form, message, Modal, Popconfirm, Space, Table, Tooltip} from "antd";
import React, {useRef, useState} from "react";
import {BarsOutlined, CheckOutlined, CloseOutlined, EditOutlined, PlusOutlined, SettingFilled} from "@ant-design/icons";
import {globalApi, handleGloblApi} from "@/services/admin-api/globalApi";
import {Order, orderStatus, orderStatusSelect} from "@/pages/Order/Management";
import {Access, useAccess} from "umi";

export type OrderCost = {
  ocId: number
  orderId: number
  workerId: number
  workerNickName: string
  usId: number
  usNickName: string
  ocMoney: number
  ocType: number
  usSplitType: number
  usSplitProportion: number
  ocSettlementTime: string
  ocSettlementUserId: number
  ocSettlementUserName: string
  ocDesc: string
  delFlag: boolean
  createTime: string
  createUserId: number
  createUserName: string
  updateTime: string
  updateUserId: number
  updateUserName: string
}

export const ocType = await globalApi('/config/dict', {key: 'oc_type'})
const storeSelect = await globalApi('/store/select', {})
export const usSplitType = [{label: '店主', value: 0}, {label: '店长', value: 1}, {label: '城市合伙人', value: 2},]

export default () => {

  const access = useAccess()

  const actionRef = useRef<ActionType>();
  const ocActionRef = useRef<ActionType>();
  const [ocTypeForm, setOcTypeForm] = useState(0)

  const columns: ProColumns<Order>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: 'ID', dataIndex: 'orderId', valueType: 'text', width: 135, copyable: true},
    {title: '名称', dataIndex: 'customerName', valueType: 'text'},
    {title: '电话', dataIndex: 'customerPhone', valueType: 'text', width: 120, copyable: true},
    {
      title: '状态',
      dataIndex: 'orderStatus',
      valueType: 'select',
      valueEnum: orderStatus,
      fieldProps: {options: orderStatusSelect}
    },
    {title: '时间', dataIndex: 'serviceTime', valueType: 'dateTime', hideInSearch: true,},
    {
      title: '服务时间', dataIndex: 'serviceTime', valueType: 'dateTimeRange', hideInTable: true, search: {
        transform: (value) => {
          return {serviceTimeStart: value[0], serviceTimeEnd: value[1],};
        },
      },
    },
    {title: '距离(km)', dataIndex: 'distance', valueType: 'digit', ellipsis: true, hideInSearch: true},
    {
      title: '店铺',
      dataIndex: 'storeId',
      valueType: 'select',
      fieldProps: {options: storeSelect.data, showSearch: true}
    },
    {title: '起点', dataIndex: 'startAddress', valueType: 'text', ellipsis: true},
    {title: 'startAddressLng', dataIndex: 'startAddressLng', valueType: 'digit', hideInSearch: true,},
    {title: 'startAddressLat', dataIndex: 'startAddressLat', valueType: 'digit', hideInSearch: true,},
    {title: '新家', dataIndex: 'newAddress', valueType: 'text', ellipsis: true},
    {title: 'newAddressLng', dataIndex: 'newAddressLng', valueType: 'digit', hideInSearch: true,},
    {title: 'newAddressLat', dataIndex: 'newAddressLat', valueType: 'digit', hideInSearch: true,},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {
      title: '创建时间', dataIndex: 'createTime', valueType: 'dateTimeRange', hideInTable: true, search: {
        transform: (value) => {
          return {createTimeStart: value[0], createTimeEnd: value[1],};
        },
      },
    },
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {title: '交款时间', dataIndex: 'handInTime', valueType: 'dateTime', hideInSearch: true,},
    {
      title: '交款时间', dataIndex: 'handInTimeSearch', valueType: 'dateTimeRange', hideInTable: true, search: {
        transform: (value) => {
          return {handInTimeStart: value[0], handInTimeEnd: value[1],};
        },
      },
    },
    {
      title: '交款', dataIndex: 'handInTimeStatus', valueType: 'select', hideInTable: true,
      fieldProps: {options: [{label: '已交款', value: 1}, {label: '未交款', value: 0}]}
    },
    {title: '交款用户ID', dataIndex: 'handInUserId', valueType: 'digit', hideInSearch: true,},
    {title: '交款用户', dataIndex: 'handInUserName', valueType: 'text', hideInSearch: true,},
    {title: '核销时间', dataIndex: 'writeOffTime', valueType: 'dateTime', hideInSearch: true,},
    {
      title: '核销时间', dataIndex: 'writeOffTimeSearch', valueType: 'dateTimeRange', hideInTable: true, search: {
        transform: (value) => {
          return {writeOffTimeStart: value[0], writeOffTimeEnd: value[1],};
        },
      },
    },
    {
      title: '核销', dataIndex: 'writeOffTimeStatus', valueType: 'select', hideInTable: true,
      fieldProps: {options: [{label: '已核销', value: 1}, {label: '未核销', value: 0}]}
    },
    {title: '核销用户ID', dataIndex: 'writeOffUserId', valueType: 'digit', hideInSearch: true,},
    {title: '核销用户', dataIndex: 'writeOffUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Access accessible={access.canAuth('cost:list')}>
          <Tooltip key={'cost_' + record.orderId} title={"查看成本"}>
            <Button
              size="small" icon={<BarsOutlined/>} type="primary"
              onClick={async () => {
                setIsModalOpen(true)
                setOrderId(record.orderId)
              }}
            />
          </Tooltip>
        </Access>
        ,
      ],
      valueType: 'option',
    },
  ];

  const ocColumns: ProColumns<OrderCost>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: 'ID', dataIndex: 'ocId', valueType: 'digit'},
    {title: '成本类型', dataIndex: 'ocType', valueType: 'select', fieldProps: {options: ocType.data}},
    {title: '订单ID', dataIndex: 'orderId', valueType: 'text'},
    {title: '工作人员', dataIndex: 'workerNickName', valueType: 'text'},
    {title: '用户', dataIndex: 'usNickName', valueType: 'text'},
    {title: '分成类型', dataIndex: 'usSplitType', valueType: 'select', fieldProps: {options: usSplitType}},
    {title: '金额', dataIndex: 'ocMoney', valueType: 'money'},
    {title: '描述', dataIndex: 'ocDesc', valueType: 'text'},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {title: '核销时间', dataIndex: 'ocSettlementTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '核销用户ID', dataIndex: 'ocSettlementUserId', valueType: 'digit', hideInSearch: true,},
    {title: '核销用户', dataIndex: 'ocSettlementUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        record.ocSettlementTime === null ?
          <Tooltip key={'editcost_' + record.orderId} title={"编辑成本"}>
            <Button
              size="small" icon={<EditOutlined/>} type="primary"
              onClick={async () => {
                handleModalOpen(true)
                form.setFieldsValue({
                  ...record,
                  worker: {label: record.workerNickName, value: record.workerId},
                  us: {label: record.usNickName, value: record.usId}
                })
              }}
            /></Tooltip> : '',
        record.ocSettlementTime === null ?
          <Access accessible={access.canAuth('check:writeoff')}>
            <Tooltip key={'removecost_' + record.orderId} title={"核销单条成本 - 核销此成本"}>
              <Popconfirm
                title="核销成本" description="确认核销掉单条成本？"
                onConfirm={async () => {
                  const r = await handleGloblApi('/finance/costSettlement', {ocId: record.ocId})
                  if (r) {
                    ocActionRef.current?.reload()
                  }
                }} okText="Yes" cancelText="No">
                <Button size="small" icon={<CheckOutlined/>} type="primary"/>
              </Popconfirm>
            </Tooltip></Access> : '',
        record.ocSettlementTime === null ?
          <Access accessible={access.canAuth('cost:remove')}>
            <Tooltip key={'setcost_' + record.orderId} title={"删除此成本 - 已核销不可删除"}>
              <Popconfirm
                title="删除成本" description="确认删除掉单条成本？"
                onConfirm={async () => {
                  const r = await handleGloblApi('/finance/costRemove', {ocId: record.ocId})
                  if (r) {
                    ocActionRef.current?.reload()
                  }
                }} okText="Yes" cancelText="No">
                <Button size="small" danger icon={<CloseOutlined/>} type="primary"/>
              </Popconfirm>
            </Tooltip></Access> : '',
      ],
      valueType: 'option',
    },
  ];

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectRows, setSelectedRows] = useState<Order[]>([]);
  const [list, setList] = useState<Order[]>([]);

  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)

  // const [ocList, setOcList] = useState<OrderCost[]>()
  const [orderId, setOrderId] = useState<number>()

  const [modalOpen, handleModalOpen] = useState(false)

  const [form] = Form.useForm()

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<Order>
      columns={columns} actionRef={actionRef} search={{span: 4}}
      rowSelection={{
        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
        // 注释该行则默认不显示下拉选项
        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE,
          {
            key: 'handin',
            text: '等待交款',
            onSelect: (changeableRowKeys) => {
              const selectrows = list.filter(l => l.handInTime === null)
              setSelectedRows(selectRows)
              const selectrowkeys = selectrows.map(s => s.orderId)
              setSelectedRowKeys(selectrowkeys)
              if (selectrows.length === 0) {
                message.info("没有需要交款的订单")
              }
            },
          }, {
            key: 'writeoff',
            text: '等待核销',
            onSelect: (changeableRowKeys) => {
              const selectrows = list.filter(l => l.writeOffTime === null)
              setSelectedRows(selectRows)
              const selectrowkeys = selectrows.map(s => s.orderId)
              setSelectedRowKeys(selectrowkeys)
              if (selectrows.length === 0) {
                message.info("没有需要核销的订单")
              }
            },
          }],
        // defaultSelectedRowKeys: [1],
        alwaysShowAlert: true,
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys: React.Key[], selectedRows: Order[]) => {
          // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          setSelectedRowKeys(selectedRowKeys)
          setSelectedRows(selectedRows)
        }
      }}
      tableAlertRender={(
        {
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => {
        console.log(selectedRowKeys, selectedRows, selectRows)
        // setSelectedRowKeys([...selectedRowKeys])
        return (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <Button type={"link"} disabled={selectedRowKeys.length === 0} style={{marginInlineStart: 8}}
                      onClick={onCleanSelected}>取消选择</Button>
            </span>
            <span>可交款： {selectRows.filter(s => s.handInTime === null).length} 个</span>
            <span>可核销： {selectRows.filter(s => s.writeOffTime === null).length} 个</span>
          </Space>
        );
      }}
      tableAlertOptionRender={() => {
        return (
          <Space>
            <Access accessible={access.canAuth('check:payment')}>
              <Popconfirm
                title="交款"
                description={`确认交款 ${selectedRowKeys.length} 条订单 ？`}
                onConfirm={async () => {
                  const r = await handleGloblApi('/finance/handIn', {orderIds: selectedRowKeys})
                  if (r) {
                    setSelectedRows([])
                    setSelectedRowKeys([])
                    actionRef.current?.reload()
                  }
                }}
                okText="Yes"
                cancelText="No"
              >
                <Button disabled={selectRows.filter(s => s.handInTime === null).length == 0} type={"link"}>交款</Button>
              </Popconfirm>
            </Access>
            <Access accessible={access.canAuth('check:writeoff')}>
              <Popconfirm
                title="核销"
                description={`确认核销 ${selectedRowKeys.length} 条订单 ？`}
                onConfirm={async () => {
                  const r = await handleGloblApi('/finance/writeOff', {orderIds: selectedRowKeys})
                  if (r) {
                    setSelectedRows([])
                    setSelectedRowKeys([])
                    actionRef.current?.reload()
                  }
                }}
                okText="Yes"
                cancelText="No"
              >
                <Button disabled={selectRows.filter(s => s.writeOffTime === null).length == 0}
                        type={"link"}>核销</Button>
              </Popconfirm>
            </Access>
          </Space>
        );
      }}
      request={async (param) => {
        console.log('param = ', param)
        const hide = message.loading('正在加载表格');
        if (!access.canAuth('check:list:search')) {
          message.error(`无权限 check:list:search`)
          return {success: true, data: [], total: 0}
        }
        const r = await globalApi('/finance/table', param)
        console.log('r = ', r)
        hide();
        message.success('Loading successfully');
        setList(r.data.data)
        setSelectedRows([])
        setSelectedRowKeys([])
        return {success: r.success, data: r.data.data, total: r.data.total}
      }} rowKey={(record) => record.orderId}
      columnsState={{
        defaultValue: {
          handInUserId: {show: false},
          writeOffUserId: {show: false},
          startAddressLng: {show: false},
          startAddressLat: {show: false},
          newAddressLng: {show: false},
          newAddressLat: {show: false},
          delFlag: {show: false},
          createUserId: {show: false},
          createUserName: {show: false},
          createTime: {show: false},
          updateUserId: {show: false},
          updateUserName: {show: false},
          updateTime: {show: false},
        }
      }}/>

    <Modal
      width={1200} open={isModalOpen} onOk={() => setIsModalOpen(false)} onCancel={() => setIsModalOpen(false)}>
      <ProTable
        headerTitle={
          <Access accessible={access.canAuth('cost:add')}>
            <Tooltip title={"添加成本"}>
              <Button
                size={"small"} type={"primary"} icon={<PlusOutlined/>} onClick={() => {
                handleModalOpen(true)
                form.setFieldsValue({orderId})
              }}/>
            </Tooltip></Access>} actionRef={ocActionRef}
        search={false} columns={ocColumns} rowKey={(record) => record.ocId} params={{orderId}}
        request={async (param) => {
          console.log('param = ', param)
          const hide = message.loading('正在加载表格');
          const r = await globalApi('/finance/costTable', param)
          console.log('r = ', r)
          hide();
          message.success('Loading successfully');
          setList(r.data.data)
          return {success: r.success, data: r.data.data, total: r.data.total}
        }} columnsState={{
        defaultValue: {
          delFlag: {show: false},
          createUserId: {show: false},
          updateUserId: {show: false},
          ocSettlementUserId: {show: false},
        }
      }}/>
    </Modal>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/finance/costSaveOrUpdate', value)

        if (success) {
          ocActionRef.current?.reload();
          return true
        }

      }}
    >
      <ProFormDigit label="ocId" name="ocId" hidden/>
      <ProFormDigit label="订单ID" name="orderId" hidden/>

      <ProFormDigit name={"workerId"} hidden/>
      <ProFormText name={"workerNickName"} hidden/>

      <ProFormSelect
        label="成本类型" showSearch rules={[{required: true}]} name="ocType" initialValue={ocTypeForm}
        options={ocType.data} fieldProps={{
        onSelect: (val) => {
          setOcTypeForm(val)
        }
      }}/>

      {
        ocTypeForm === 1 ? <>
          <ProFormSelect label={"用户分成类型"} rules={[{required: true}]} name={"usSplitType"} options={usSplitType}/>

          <ProFormSelect
            label="用户" tooltip={"工作人员ID和用户ID只能选一个 - 同时选择 工作人员ID优先级最高"} fieldProps={{
            labelInValue: true,
            showSearch: true, onSelect: (value) => {
              form.setFieldsValue({usId: value.value, usNickName: value.label})
            }
          }} rules={[{required: true}]} dependencies={['usSplitType']}
            name="us" params={{orderId}} request={async (param) => {
            const r = await globalApi('/finance/userSelect', param)
            return r.data
          }}/>

          <ProFormDigit label={"用户分成比例"} rules={[{required: true}]} name={"usSplitProportion"} addonAfter={"%"}/>
        </> : <>
          <ProFormSelect
            label="工作人员" tooltip={"工作人员ID和用户ID只能选一个 - 同时选择 工作人员ID优先级最高"} fieldProps={{
            labelInValue: true,
            showSearch: true, onSelect: (value) => {
              form.setFieldsValue({workerId: value.value, workerNickName: value.label})
            }
          }}
            name="worker" params={{orderId}} request={async (param) => {
            const r = await globalApi('/finance/workerSelect', param)
            return r.data
          }}/>
        </>
      }

      <ProFormMoney label="成本金额" rules={[{required: true}]} name="ocMoney"/>
      <ProFormText label="成本描述" rules={[{required: true}]} name="ocDesc"/>

      <ProFormDigit name={"usId"} hidden/>
      <ProFormText name={"usNickName"} hidden/>

    </ModalForm>

  </PageContainer>
}
